<?php

namespace App\Admin\Controllers;


use App\Models\NewsExtra;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;

class NewsExtraController extends BaseController
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        if ($newsId = request('newsId')) {
            session(['newsId' => $newsId]);
        } else {
            session(['newsId' => null]);
        }
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(NewsExtra::class, function (Grid $grid) {

            $newsId = session('newsId');
            $grid->id('ID')->sortable();
            $grid->model()->where('news_id',$newsId);
            $grid->column('title', '标题');

        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(NewsExtra::class, function (Form $form) {

            $menu = session('menu');
            $newsId = session('newsId');
            $show = $menu->newsEditShow;

            $form->hidden('news_id')->default($newsId);
            if (!$show || strstr($show, 'title'))
            $form->text('title', '标题');
            if (!$show || strstr($show, 'content'))
            $form->editor('content', '内容');
            $form->saved(function (Form $form) use ($newsId) {
                return redirect("/admin/newsExtra?newsId={$newsId}");
            });
        });
    }
}
